package com.sunlg.smarthome.ui.main;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunlg.smarthome.R;
import com.sunlg.smarthome.base.App;
import com.sunlg.smarthome.base.BaseActivity;
import com.sunlg.smarthome.base.C;
import com.sunlg.smarthome.data.remote.MySubscriber;
import com.sunlg.smarthome.data.weather.Weather;
import com.sunlg.smarthome.data.weather.WeatherWrapper;
import com.sunlg.smarthome.service.ExitService;
import com.sunlg.smarthome.ui.curtain.CurtainListActivity;
import com.sunlg.smarthome.ui.environment.TempHumListActivity;
import com.sunlg.smarthome.ui.fire.FireDeviceListActivity;
import com.sunlg.smarthome.ui.gateway.GatewayActivity;
import com.sunlg.smarthome.ui.guard.SecurityDeviceListActivity;
import com.sunlg.smarthome.ui.light.LightListActivity;
import com.sunlg.smarthome.ui.personal.NotificationActivity;
import com.sunlg.smarthome.ui.personal.PersonalActivity;
import com.sunlg.smarthome.ui.plant.PlantManageActivity;
import com.sunlg.smarthome.ui.warning.WarningActivity;
import com.sunlg.smarthome.utils.PreferHelper;

import butterknife.BindView;

public class MainActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {

    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;

    @BindView(R.id.nav_view)
    NavigationView navigationView;

    @BindView(R.id.cv_light)
    CardView cvLight;
    @BindView(R.id.cv_curtian)
    CardView cvCurtain;
    @BindView(R.id.cv_environment)
    CardView cvEnvironment;
    @BindView(R.id.cv_plant)
    CardView cvPlant;
    @BindView(R.id.cv_guard)
    CardView cvGuard;
    @BindView(R.id.cv_fire)
    CardView cvFire;

    @BindView(R.id.btn_menu)
    Button btnMenu;
    @BindView(R.id.temperature)
    TextView tvTemperature;
    @BindView(R.id.tv_addr_and_desc)
    TextView tvCityAndDesc;
    @BindView(R.id.tv_dir)
    TextView tvDir;
    @BindView(R.id.tv_sc)
    TextView tvSc;
    @BindView(R.id.tv_hum_value)
    TextView tvHum;
    @BindView(R.id.tv_fl_value)
    TextView tvFl;

    private Toolbar mToolbar;

    // 是否退出
    private static boolean isExit = false;

    private Weather weather;

    private String city;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_main;
    }

    @Override
    protected void setupToolBar(Toolbar toolbar) {
        this.mToolbar = toolbar;
        //设置状态栏透明
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT); //也可以设置成灰色透明的，比较符合Material Design的风格
        }
        //布局扩展到状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

        //toolb标题栏透明
        toolbar.getBackground().setAlpha(0);

        toolbar.setTitleTextColor(getResources().getColor(R.color.colorPrimary));
        //margin-top=状态栏高度
        final RelativeLayout.LayoutParams param = (RelativeLayout.LayoutParams) toolbar.getLayoutParams();
        param.setMargins(0, getStatusBarHeight(this), 0, 0);
        toolbar.setLayoutParams(param);
    }

    @Override
    protected void init() {
        city = "桂林";

    }

    @Override
    protected void initView() {
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.setDrawerIndicatorEnabled(true);
        toggle.syncState();

        navigationView.setNavigationItemSelectedListener(this);
        navigationView.setOnClickListener(this);
        btnMenu.setOnClickListener(this);

        LinearLayout linearLayout = (LinearLayout) navigationView.getHeaderView(0);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                overlay(PersonalActivity.class);
            }
        });

        TextView tvName = (TextView)linearLayout.findViewById(R.id.tv_name);
        tvName.setText(App.getInstance().getPreferHelper().getString(C.PreKey.USER_NAME, "未知"));

        cvLight.setOnClickListener(this);
        cvCurtain.setOnClickListener(this);
        cvEnvironment.setOnClickListener(this);
        cvPlant.setOnClickListener(this);
        cvGuard.setOnClickListener(this);
        cvFire.setOnClickListener(this);

        //获取实况天气
        WeatherWrapper weatherWrapper = new WeatherWrapper();
        MySubscriber<Weather> weatherSubscriber = new MySubscriber<Weather>() {
            @Override
            public void onSuccess(Weather data) {
                weather = data;
                setWeather();
            }

            @Override
            public void _onError(Throwable e) {
                Log.e("1", e.getMessage());
            }
        };
        weatherWrapper.getNow(weatherSubscriber, city);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_menu:
                if(!drawer.isDrawerOpen(GravityCompat.START)){
                    drawer.openDrawer(GravityCompat.START);
                }
                break;
            case R.id.cv_light:
                overlayTo(LightListActivity.class);
                break;
            case R.id.cv_curtian:
                overlayTo(CurtainListActivity.class);
                break;
            case R.id.cv_environment:
                overlayTo(TempHumListActivity.class);
                break;
            case R.id.cv_plant:
                overlayTo(PlantManageActivity.class);
                break;
            case R.id.cv_guard:
                overlayTo(SecurityDeviceListActivity.class);
                break;
            case R.id.cv_fire:
                overlayTo(FireDeviceListActivity.class);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
/*        if (id == R.id.action_settings) {
            return true;
        }*/

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_bind_gateway) {
            overlay(GatewayActivity.class);
        }else if(id == R.id.nav_warning){
            overlay(WarningActivity.class);
        }else if(id == R.id.nav_personal){
            overlay(PersonalActivity.class);
        }else if(id == R.id.nav_notification){
            overlay(NotificationActivity.class);
        }else if(id == R.id.nav_setting){
            overlay(SettingActivity.class);
        }else if(id == R.id.nav_e){
/*            Intent intent = new Intent(this, ExitService.class);
            startService(intent);*/
            System.exit(0);
        }

        //drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    /**
     * 显示实况天气
     */
    private void setWeather(){
        tvTemperature.setText(weather.getTmp()+"°");
        tvCityAndDesc.setText(weather.getCity()+" | "+weather.getDesc());
        tvDir.setText(weather.getDir());
        tvSc.setText(weather.getSc()+"级");
        tvFl.setText(weather.getFl()+"°");
        tvHum.setText(weather.getHum()+"%");
    }


    //按两次返回键退出应用
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(drawer.isDrawerOpen(GravityCompat.START)){
                drawer.closeDrawer(GravityCompat.START);
            }else {
                exit();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            toast("再按一次退出应用");

            // 利用handler延迟发送更改状态信息
            handler.sendEmptyMessageDelayed(0, 2000);
        } else {
            //注销退出
/*            Intent intent = new Intent(this, ExitService.class);
            startService(intent);*/
            System.exit(0);
        }
    }

    /**
     * 获取状态栏高度
     *
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        java.lang.reflect.Field field = null;
        int x = 0;
        int statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
            return statusBarHeight;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusBarHeight;
    }

    private boolean isBindGateway(){
        return new PreferHelper(App.getInstance(), "gateway").getBoolean("exist", false);
    }

    private void showNoBindGateway(){
        RelativeLayout view = (RelativeLayout)findViewById(R.id.content_main);
        Snackbar.make(view, "您还没绑定网关", Snackbar.LENGTH_LONG)
                .setAction("绑定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        overlay(GatewayActivity.class);
                    }
                })
                .show();
    }

    private void overlayTo(Class<?> cls){
        if(isBindGateway()){
            overlay(cls);
        }else {
            showNoBindGateway();
        }
    }
}
